<template>
    <div class="white-box">
        <div class="table-mb">
            <el-button type="primary" @click="clickAddOne">添加</el-button>
        </div>
        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">公告标题：</span>
                <el-input placeholder="输入公告标题" v-model.trim="search_text" size="default" clearable></el-input>
            </div>
            <div class="task-one__btn clearfix">
                <el-button type="primary" :loading="search_btn" :icon="Search" @click="handleSearch">搜索</el-button>
            </div>
        </div>
        <el-table
            class="table-mb"
            :data="arr_data"
            v-loading="loading"
            :header-cell-style="{ background: '#F5F7FA' }"
            element-loading-background="rgba(255, 255, 255, 0.5)"
        >
            <el-table-column prop="article_id" label="ID" width="110"></el-table-column>
            <el-table-column prop="title" label="公告标题"></el-table-column>
            <el-table-column prop="on_time_label" label="发布时间" width="220"></el-table-column>
            <el-table-column label="操作" class-name="operation-nav" width="200" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" class="theme-btn" @click="clickOneEdit(row)">编辑</el-button>
                    <el-popconfirm title="是否确定删除？" confirm-button-text="确定" cancel-button-text="取消" @confirm="clickOneDel(row)">
                        <template #reference>
                            <el-button link type="primary" class="theme-btn">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>

        <!-- 添加/编辑文字公告 -->
        <el-dialog
            v-model="dialogOne"
            :title="`${oneClass == 1 ? '添加' : '编辑'}公告`"
            top="7vh"
            :close-on-click-modal="false"
            width="940px"
            :append-to-body="true"
            :destroy-on-close="true"
            @close="closeOne"
        >
            <el-form ref="ruleOneRef" :model="ruleOneForm" :rules="ruleOneCheck" label-width="140px">
                <el-form-item label="公告标题" prop="title">
                    <el-input v-model.trim="ruleOneForm.title" clearable placeholder="请输入公告标题" />
                </el-form-item>
                <el-form-item label="选择封面" prop="img_paths">
                    <div class="img-list" v-if="ruleOneForm.img_paths">
                        <div class="img-selects">
                            <el-image
                                class="img-selects__pic"
                                :src="proxy.imgUrl + ruleOneForm.img_paths + '!img_400'"
                                :preview-src-list="srcList"
                                fit="cover"
                            />
                            <div class="img-del" @click.stop="delImg">
                                <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                            </div>
                        </div>
                    </div>
                    <div class="img-box flexs-center" @click.stop="showImg = true" v-else>
                        <el-icon color="#999" size="26px">
                            <UploadFilled />
                        </el-icon>
                    </div>
                </el-form-item>
                <el-form-item label="公告内容" prop="valueHtml">
                    <div class="editor-box">
                        <Toolbar style="border-bottom: 1px solid #ccc; width: 720px" :editor="editorRef" :defaultConfig="toolbarConfig" mode="default" />
                        <Editor
                            style="height: 360px; overflow-y: hidden; width: 720px"
                            v-model="ruleOneForm.valueHtml"
                            :defaultConfig="editorConfig"
                            mode="default"
                            @onCreated="handleCreated"
                        />
                    </div>
                </el-form-item>
                <el-form-item>
                    <div class="flexs" style="margin-top: 20px">
                        <el-button type="primary" :loading="form_loading" @click="submitOneForm(ruleOneRef)">{{
                            oneClass == 1 ? "确认添加" : "确认保存"
                        }}</el-button>
                        <el-button @click="resetOneForm(ruleOneRef)">取消</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 图片库 -->
        <picture-library :show="showImg" :select_multiple="false" @close="showImg = false" @select="selectImg"> </picture-library>
    </div>

    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, watch, reactive, shallowRef, onBeforeUnmount } from "vue"
import { useRouter } from "vue-router"
import { UploadFilled, CloseBold, Search } from "@element-plus/icons-vue"
import OneLoad from "@mixins/one-load"
import GoBack from "@components/GoBack.vue"
import "@wangeditor/editor/dist/css/style.css"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"
import PictureLibrary from "@components/PictureLibrary.vue"

const router = useRouter()
const { proxy } = getCurrentInstance()

onMounted(() => {
    getList()
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    ruleOneRef.value = null

    if (editorRef.value == null) return
    editorRef.value.destroy()
})

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, totalNums, search_text, search_btn, pubParams, pubRefreshParams, getdata } = OneLoad()

// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    pubParams(getList)
})

function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
        so: search_text.value,
    }
    getdata("supplier/declare/index", params)
}

const handleSearch = () => {
    search_btn.value = true
    pubRefreshParams(getList)
}

/**
 * 添加/编辑公告
 * @param {Boolean} dialogOne 弹窗状态
 * @param {Number} oneClass 1是添加，2是编辑
 * @param {Array} ruleOneRef 表单规则
 * @param {Object} ruleOneForm  表单字段
 * @param {Object} ruleOneCheck  表单提示
 */
const form_loading = ref(false)
const dialogOne = ref(false)
const oneClass = ref(1)
const ruleOneRef = ref(null)
const ruleOneForm = reactive({
    id: "",
    title: "",
    img_paths: "",
    valueHtml: "",
})
const ruleOneCheck = reactive({
    title: [{ required: true, message: "请输入公告标题", trigger: "blur" }],
    img_paths: [{ required: true, message: "请选择公告封面", trigger: "change" }],
    valueHtml: [{ required: true, validator: validDesc, trigger: "blur" }],
})
// 公告内容-自定义富文本校验规则
function validDesc(rule, value, callback) {
    let regu = editorRef.value.getText()
    if (regu === "") {
        callback(new Error("请输入公告内容"))
    } else {
        callback()
    }
}
const submitOneForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            // const texts = editorRef.value.getText()
            let htmls = ""
            if (valueHtml.value) {
                htmls = valueHtml.value.replace(/\bhttps?:\/\/(.*?)\/+/gi, "") // 去除图片根域名以及根域名后面的'/'
            }
            form_loading.value = true
            let data = {
                title: ruleOneForm.title,
                thumb: ruleOneForm.img_paths,
                content: htmls,
            }
            if (oneClass.value == 2) {
                data.article_id = ruleOneForm.id
            }
            let url = oneClass.value == 1 ? "supplier/declare/add" : "supplier/declare/update"
            proxy.$axios
                .post(url, data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogOne.value = false
                        proxy.$message({ message: `${oneClass.value == 1 ? "添加成功！" : "编辑成功！"}`, type: "success" })
                        pubRefreshParams(getList)
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetOneForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    dialogOne.value = false
    editorRef.value.setHtml("<p></p>") // 重置富文本
}
const clickAddOne = () => {
    oneClass.value = 1
    dialogOne.value = true
}
const closeOne = () => {
    resetOneForm(ruleOneRef.value)
    dialogOne.value = false
}
// 删除
const clickOneDel = (row) => {
    proxy.$axios
        .post("supplier/declare/delete", {
            article_id: row.article_id,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

// 编辑时
const clickOneEdit = (row) => {
    dialogOne.value = true
    oneClass.value = 2
    getDetail(row.article_id)
}
function getDetail(eid) {
    proxy.$axios
        .get("article/update", {
            params: {
                article_id: eid,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                ruleOneForm.valueHtml = result.detail.content.replace(/<img [^>]*src=['"]/g, `<img src="${proxy.imgUrl}`) // 往图片追加根域名和'/'
                ruleOneForm.id = result.detail.cate_id
                ruleOneForm.title = result.detail.title
                if (result.detail && result.detail.thumb) {
                    ruleOneForm.img_paths = result.detail.thumb
                    srcList.value.push(proxy.imgUrl + result.detail.thumb)
                }
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

/**
 * 富文本编辑器
 * @param {Object} editorConfig 编辑器配置
 * @param {Object} toolbarConfig 工具栏配置
 * @param {Function} createEditor 创建编辑器
 * @param {Function} createToolbar 创建工具栏
 * @param {Function} handleChange 编辑器内容变化
 */
const editorRef = shallowRef() // 编辑器实例，必须用 shallowRef
const toolbarConfig = {
    // 排除不需要的菜单
    excludeKeys: ["insertLink", "insertImage", "editImage", "viewImageLink", "group-video", "emotion", "fullScreen"],
}
const editorConfig = { placeholder: "请输入内容...", MENU_CONF: {} }
const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
editorConfig.MENU_CONF["uploadImage"] = {
    // 自定义上传
    async customUpload(file, insertFn) {
        let data = new FormData()
        data.append("from", "article")
        data.append("image", file)
        proxy.$axios
            .post("upload/image", data)
            .then((res) => {
                if (res.data.code == 0) {
                    let url = proxy.imgUrl + res.data.data.path
                    insertFn(url) // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
                } else {
                    proxy.$message({message:res.data.msg,type:"error"})
                }
            })
            .catch((err) => {})
    },
}

/**
 * 添加图片
 * @property {Boolean} showImg 显示图片库
 * @property {Function} selectImg 选择图片
 */
const showImg = ref(false)
const srcList = ref([])
const selectImg = (val) => {
    showImg.value = false
    ruleOneForm.img_paths = val[0].photo
    srcList.value.push(proxy.imgUrl + val[0].photo)
}
const delImg = () => {
    ruleOneForm.img_paths = ""
    srcList.value = []
}
</script>
<script>
export default {
    name: "SupplierNotice",
}
</script>

<style lang="less" scoped>
.table-mb {
    margin: @margin-mdl 0px;
}
.editor-box {
    border: 1px solid #ccc;
    border-radius: 2px;
}
:deep(.detail-item__right) {
    overflow: inherit !important;
}
</style>
